<!DOCTYPE html>
<html  lang="zh">
<head>
    <meta charset="utf-8" />

<meta name="generator" content="Hexo 3.8.0" />

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

<title>【iOS 开发】Runtime 总结 - OBJC.VIP</title>


    <meta name="description" content="一、Runtime是什么？">
<meta name="keywords" content="iOS 开发">
<meta property="og:type" content="article">
<meta property="og:title" content="【iOS 开发】Runtime 总结">
<meta property="og:url" content="https://objcvip.github.io/RuntimeSummary/index.html">
<meta property="og:site_name" content="OBJC.VIP">
<meta property="og:description" content="一、Runtime是什么？">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://objcvip.github.io/images/og_image.png">
<meta property="og:updated_time" content="2019-09-08T09:24:18.673Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【iOS 开发】Runtime 总结">
<meta name="twitter:description" content="一、Runtime是什么？">
<meta name="twitter:image" content="https://objcvip.github.io/images/og_image.png">







<link rel="icon" href="/images/favicon.svg">


<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.7.2/css/bulma.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu:400,600|Source+Code+Pro">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@9.12.0/styles/atom-one-dark.css">


    
    
    
    <style>body>.footer,body>.navbar,body>.section{opacity:0}</style>
    

    
    
    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lightgallery@1.6.8/dist/css/lightgallery.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/css/justifiedGallery.min.css">
    

    
    

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/outdatedbrowser@1.1.5/outdatedbrowser/outdatedbrowser.min.css">


    
    
    
    

<link rel="stylesheet" href="/css/back-to-top.css">


    
    

    
    
    
    

    
    
<link rel="stylesheet" href="/css/progressbar.css">
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

    
    
    


<link rel="stylesheet" href="/css/style.css">
</head>
<body class="is-1-column">
    <nav class="navbar navbar-main">
    <div class="container">
        <div class="navbar-brand is-flex-center">
            <a class="navbar-item navbar-logo" href="/">
            
                <img src="/images/logo.svg" alt="【iOS 开发】Runtime 总结" height="28">
            
            </a>
        </div>
        <div class="navbar-menu">
            
            <div class="navbar-start">
                
                <a class="navbar-item"
                href="/">首页</a>
                
                <a class="navbar-item"
                href="/archives">归档</a>
                
                <a class="navbar-item"
                href="/categories">分类</a>
                
                <a class="navbar-item"
                href="/tags">标签</a>
                
                <a class="navbar-item"
                href="/links">友链</a>
                
                <a class="navbar-item"
                href="/about">关于</a>
                
            </div>
            
            <div class="navbar-end">
                
                
                
                <a class="navbar-item search" title="搜索" href="javascript:;">
                    <i class="fas fa-search"></i>
                </a>
                
            </div>
        </div>
    </div>
</nav>
    
    <section class="section">
        <div class="container">
            <div class="columns">
                <div class="column is-12 has-order-2 column-main"><div class="card">
    
    <div class="card-content article ">
        
        <div class="level article-meta is-size-7 is-uppercase is-mobile is-overflow-x-auto">
            <div class="level-left">
                <time class="level-item has-text-grey" datetime="2017-04-23T16:00:00.000Z">2017-04-24</time>
                
                <div class="level-item">
                <a class="has-link-grey -link" href="/categories/iOS-开发/">iOS 开发</a>
                </div>
                
                
                <span class="level-item has-text-grey">
                    
                    
                    5 分钟 读完 (大约 708 个字)
                </span>
                
                
            </div>
        </div>
        
        <h1 class="title is-size-3 is-size-4-mobile has-text-weight-normal">
            
                【iOS 开发】Runtime 总结
            
        </h1>
        <div class="content">
            <h3 id="一、Runtime是什么？"><a href="#一、Runtime是什么？" class="headerlink" title="一、Runtime是什么？"></a>一、Runtime是什么？</h3><a id="more"></a>
<p>Runtime 运行时，就是系统在运行的时候的一些机制，其中最主要的是消息机制。<br>Runtime 基本是用C和汇编编写的。</p>
<h4 id="OC与C语言在函数调用上的区别："><a href="#OC与C语言在函数调用上的区别：" class="headerlink" title="OC与C语言在函数调用上的区别："></a>OC与C语言在函数调用上的区别：</h4><p>C语言：</p>
<ol>
<li>函数的调用在编译的时候就决定调用哪个函数，编译完成之后直接顺序执行，无任何二义性。</li>
<li>C语言在编译阶段调用未实现的函数就会报错。</li>
</ol>
<p>OC：</p>
<ol>
<li>函数的调用称为消息发送。属于动态调用过程。</li>
<li>在编译的时候并不能决定真正调用哪个函数。在编译阶段，可以调用任何函数，只要函数声明过。</li>
</ol>
<h3 id="二、与Runtime系统交互："><a href="#二、与Runtime系统交互：" class="headerlink" title="二、与Runtime系统交互："></a>二、与Runtime系统交互：</h3><h5 id="1-通过OC源代码"><a href="#1-通过OC源代码" class="headerlink" title="1. 通过OC源代码"></a>1. 通过OC源代码</h5><p>编译器会自动将OC代码转换成运行时代码，在运行时确定数据结构和函数。</p>
<h5 id="2-NSObject类定义的方法"><a href="#2-NSObject类定义的方法" class="headerlink" title="2. NSObject类定义的方法"></a>2. NSObject类定义的方法</h5><p>-class<br>-isKindOfClass  -isMemberOfClass<br>-respondsToSelector<br>-confirmsToProtocol<br>-methodForSelector  返回指定方法实现的地址</p>
<h5 id="3-直接调用-Runtime-库函数-Runtime-常用接口方法"><a href="#3-直接调用-Runtime-库函数-Runtime-常用接口方法" class="headerlink" title="3. 直接调用 Runtime 库函数(Runtime 常用接口方法)"></a>3. 直接调用 Runtime 库函数(Runtime 常用接口方法)</h5><p>object_getClass<br>@selector()<br>class_getClassMethod<br>class_getInstanceMethod<br>class_addMethod()<br>class_replaceMethod<br>method_exchangeImplementations<br>class_copyPropertyList<br>class_copyMethodList<br>class_copyProtocolList</p>
<h3 id="三、Runtime相关术语"><a href="#三、Runtime相关术语" class="headerlink" title="三、Runtime相关术语"></a>三、Runtime相关术语</h3><p>SEL<br>id<br>Class<br>Method<br>Ivar 成员变量<br>IMP 是一个函数指针，指向了方法的实现。<br>Cache</p>
<h3 id="四、消息发送和消息转发"><a href="#四、消息发送和消息转发" class="headerlink" title="四、消息发送和消息转发"></a>四、消息发送和消息转发</h3><h4 id="消息发送-objc-msgSend"><a href="#消息发送-objc-msgSend" class="headerlink" title="消息发送  objc_msgSend"></a>消息发送  objc_msgSend</h4><ol>
<li>通过isa指针找到所属类。</li>
<li>查找类的cache列表, 如果没有则下一步。</li>
<li>查找类的”方法列表”。</li>
<li>如果能找到与选择子名称相符的方法, 就跳至其实现代码。</li>
<li>找不到, 就沿着继承体系继续向上查找。</li>
<li>如果能找到与选择子名称相符的方法, 就跳至其实现代码。</li>
<li>找不到, 执行”消息转发”。</li>
</ol>
<h4 id="消息转发"><a href="#消息转发" class="headerlink" title="消息转发"></a>消息转发</h4><ol>
<li><p>动态方法解析</p>
<figure class="highlight objc hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">+ (<span class="hljs-built_in">BOOL</span>)resolveInstanceMethod:(SEL)selector</span><br></pre></td></tr></table></figure>
</li>
<li><p>其他接收者</p>
<figure class="highlight objc hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="hljs-keyword">id</span>)forwardingTargetForSelector:(SEL)selector</span><br></pre></td></tr></table></figure>
</li>
<li><p>消息签名</p>
<figure class="highlight objc hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="hljs-built_in">NSMethodSignature</span> *)methodSignatureForSelector:(SEL)aSelector</span><br></pre></td></tr></table></figure>
</li>
<li><p>完整的消息转发</p>
<figure class="highlight objc hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="hljs-keyword">void</span>)forwardInvocation:(<span class="hljs-built_in">NSInvocation</span> *)invocation</span><br><span class="line"><span class="hljs-comment">// invocation : 封装了与那条尚未处理的消息相关的所有细节的对象</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="五、Runtime应用"><a href="#五、Runtime应用" class="headerlink" title="五、Runtime应用"></a>五、Runtime应用</h3><ol>
<li>动态添加一个类（KVO的实现原理）</li>
<li>获取一个类的所有属性<br>（1）打印一个类的成员变量列表，属性列表，方法列表<br>（2）动态改变变量的值。<br>（3）在 NSObject 的分类中增加方法，判断是否有该属性，用于避免使用KVC赋值时崩溃。<br>（4）自动归档和解档<br>（5）字典转模型</li>
<li>动态交换方法<br>（1）交换方法<br>（2）替换系统方法<br>（3）实现多继承的效果</li>
<li>动态添加方法 performSelector<figure class="highlight objc hljs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">resolveInstanceMethod</span><br><span class="line">class_addMethod(<span class="hljs-keyword">self</span>, <span class="hljs-keyword">@selector</span>(eat), eat, <span class="hljs-string">"v@:"</span>);</span><br></pre></td></tr></table></figure>
</li>
</ol>

        </div>
        
        <div class="level is-size-7 is-uppercase">
            <div class="level-start">
                <div class="level-item">
                    <span class="is-size-6 has-text-grey has-mr-7">#</span>
                    <a class="has-link-grey -link" href="/tags/iOS-开发/">iOS 开发</a>
                </div>
            </div>
        </div>
        
        
        
    </div>
</div>





<div class="card card-transparent">
    <div class="level post-navigation is-flex-wrap is-mobile">
        
        <div class="level-start">
            <a class="level level-item has-link-grey  article-nav-prev" href="/RunloopSummary/">
                <i class="level-item fas fa-chevron-left"></i>
                <span class="level-item">【iOS 开发】RunLoop 总结</span>
            </a>
        </div>
        
        
        <div class="level-end">
            <a class="level level-item has-link-grey  article-nav-next" href="/MarkdownUsage/">
                <span class="level-item">Markdown常用语法</span>
                <i class="level-item fas fa-chevron-right"></i>
            </a>
        </div>
        
    </div>
</div>



<div class="card">
    <div class="card-content">
        <h3 class="title is-5 has-text-weight-normal">评论</h3>
        
<div id="comment-container"></div>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1.6.0/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1.6.0/dist/gitalk.min.js"></script>

<script>
    var gitalk = new Gitalk({
        clientID: '7cf9ae5a9ae4228f59ef',
        clientSecret: 'a60824892847d86dab15dae00b18a8227f9af769',
        id: '89a1eca341bacd405b3d8e6da3589681',
        repo: 'Comments',
        owner: 'objcvip',
        admin: "objcvip",
        createIssueManually: false,
        distractionFreeMode: true
    })
    gitalk.render('comment-container')
</script>

    </div>
</div>
</div>
                
                
            </div>
        </div>
    </section>
    <footer class="footer">
    <div class="container">
        <div class="level">
            <div class="level-start has-text-centered-mobile">
                <a class="footer-logo is-block has-mb-6" href="/">
                
                    <img src="/images/logo.svg" alt="【iOS 开发】Runtime 总结" height="28">
                
                </a>
                <p class="is-size-7">
                &copy; 2020 ObjC.vip&nbsp;
                All rights reserved.
                
                </p>
            </div>
            <div class="level-end">
            
            </div>
        </div>
    </div>
</footer>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.22.2/min/moment-with-locales.min.js"></script>
<script>moment.locale("zh-CN");</script>

<script>
var IcarusThemeSettings = {
    article: {
        highlight: {
            clipboard: true,
            fold: 'unfolded'
        }
    }
};
</script>


    <script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.4/dist/clipboard.min.js" defer></script>



    
    
    
    <script src="/js/animation.js"></script>
    

    
    
    
    <script src="https://cdn.jsdelivr.net/npm/lightgallery@1.6.8/dist/js/lightgallery.min.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js" defer></script>
    <script src="/js/gallery.js" defer></script>
    

    
    

<div id="outdated">
    <h6>Your browser is out-of-date!</h6>
    <p>Update your browser to view this website correctly. <a id="btnUpdateBrowser" href="http://outdatedbrowser.com/">Update
            my browser now </a></p>
    <p class="last"><a href="#" id="btnCloseUpdateBrowser" title="Close">&times;</a></p>
</div>
<script src="https://cdn.jsdelivr.net/npm/outdatedbrowser@1.1.5/outdatedbrowser/outdatedbrowser.min.js" defer></script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        outdatedBrowser({
            bgColor: '#f25648',
            color: '#ffffff',
            lowerThan: 'flex'
        });
    });
</script>


    
    
<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.5/unpacked/MathJax.js?config=TeX-MML-AM_CHTML" defer></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    MathJax.Hub.Config({
        'HTML-CSS': {
            matchFontHeight: false
        },
        SVG: {
            matchFontHeight: false
        },
        CommonHTML: {
            matchFontHeight: false
        },
        tex2jax: {
            inlineMath: [
                ['$','$'],
                ['\\(','\\)']
            ]
        }
    });
});
</script>

    
    

<a id="back-to-top" title="回到顶端" href="javascript:;">
    <i class="fas fa-chevron-up"></i>
</a>
<script src="/js/back-to-top.js" defer></script>


    
    

    
    
    
    

    
    
    
    
    


<script src="/js/main.js" defer></script>

    
    <div class="searchbox ins-search">
    <div class="searchbox-container ins-search-container">
        <div class="searchbox-input-wrapper">
            <input type="text" class="searchbox-input ins-search-input" placeholder="想要查找什么..." />
            <span class="searchbox-close ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="searchbox-result-wrapper ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: '文章',
                PAGES: '页面',
                CATEGORIES: '分类',
                TAGS: '标签',
                UNTITLED: '(无标题)',
            },
            CONTENT_URL: '/content.json',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script src="/js/insight.js" defer></script>
<link rel="stylesheet" href="/css/search.css">
<link rel="stylesheet" href="/css/insight.css">
    
</body>
</html>